<template>
  <!-- 版本管理 -->
  <div class="h100 tableSearchListFlexPage">
    <div class="tableSearchMain commonSelectWidth table-page-search-wrapper">
      <a-row :gutter="[16]">
        <a-col :md="3" :sm="16">
          <car-model-code-select
            :query="{ time: instantUpdateTime, selectAll: true }"
            :has-all="false"
            :clear="true"
            v-model="queryParam.modelCode"
            @change="refreshData"
            style="width: 100%"
          ></car-model-code-select>
        </a-col>
        <a-col :md="3" :sm="16">
          <VersionTypeSelect v-model="queryParam.versionType" @change="refreshData" :clear="true" style="width: 100%" />
        </a-col>
        <a-col :md="5" :sm="24">
          <a-select
            v-model="queryParam.ecuModuleId"
            allow-clear
            :filter-option="false"
            :placeholder="$t('pleaseSelect') + $t('lingjian')"
            mode="multiple"
            :maxTagCount="1"
            style="width: 100%"
            @search="getEcuList"
            @focus="getEcuList"
            @change="
              (val) => {
                changeEcuList(val)
                refreshData()
              }
            "
            :notFoundContent="isSearch ? $t('noData') : $t('ecuNameSearch')"
          >
            <a-select-option
              v-for="(item, index) in ecuList"
              :key="index"
              :value="item.ecuModuleId"
              :title="`${item.name}/${item.ecuModuleId}`"
            >
              {{ `${item.name}/${item.ecuModuleId}` }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :md="4" :sm="24">
          <a-input
            v-model.trim="queryParam.name"
            :placeholder="$t('pleaseInput') + $t('versionName').toLowerCase()"
            @keyup.enter="refreshData"
            allowClear
          />
        </a-col>
        <!-- 选择表单类型 -->
        <a-col :md="3" :sm="24"><!-- promptInfo -->
          <a-select
            v-model="queryParam.autoTest"
            placeholder="请选择表单类型"
            @change="refreshData"
            allowClear
            style="width: 100%"
          >
            <a-select-option v-for="(item, index) in autoTestList" :key="index" :value="item.value">
              {{ item.name }}
            </a-select-option>
          </a-select>
        </a-col>
        <a-col :md="6" :sm="24">
          <div class="searchBtns">
            <a-button-group>
              <auth-button :auth="softwarePerms.partsSoftware.view" @click="refreshData" type="primary">
                <i class="iconfont icon-chazhao"></i>
                {{ $t('inquiry') }}
              </auth-button>
              <a-button @click="initiSelectValue">
                <i class="iconfont icon-qingkong"></i>
                {{ $t('clear') }}
              </a-button>
            </a-button-group>
            <!-- 点击添加版本 -->
           <a-dropdown :disabled="false">
              <template #overlay>
                <a-menu>
                  <a-menu-item @click="handleAddEdit()" key="1">手动创建ECU版本</a-menu-item>
                  <a-menu-item @click="autoAddVersion" key="2">自动创建ECU版本</a-menu-item>
                </a-menu>
              </template>
              <auth-button :auth="softwarePerms.partsSoftware.add">
                <i class="iconfont icon-xinjian"></i>
                {{ $t('version') }}
              </auth-button>
            </a-dropdown>
          </div>
        </a-col>
      </a-row>
    </div>
    <div class="tableListMain withMinHeightTbodyBox">
      <s-table
        ref="table"
        class="h100"
        :rowKey="(record, index) => record.id"
        :columns="columns"
        :data="loadData"
        :scrollX="900"
      >
        <template slot="partNumber" slot-scope="text, record">
          {{ record.ecu ? record.ecu.ecuModuleId : '-' }}
        </template>
        <template slot="partName" slot-scope="text, record">
          {{ record.ecu ? record.ecu.name : '-' }}
        </template>
        <template slot="modelCode" slot-scope="text, record">
          <span v-if="record.modelCode">{{ record.modelCode }}</span>
          <span v-else>-</span>
        </template>
        <template slot="hardVersion" slot-scope="text">
          {{ text ? text : '-' }}
        </template>
        <template slot="hardVersionDate" slot-scope="text">
          {{ text ? text : '-' }}
        </template>
        <!-- 版本号 -->
        <template slot="versionName" slot-scope="text, record">
          <a @click="handleConfig(record, true)">
            {{ text }}
          </a>
        </template>
        <template slot="wholePackage" slot-scope="text, record">
          <span v-if="record.wholePackageCount">{{ $t('uploaded') }}</span>
          <span v-else>{{ $t('noUploaded') }}</span>
        </template>
        <template slot="differentialNum" slot-scope="text, record">
          <a
            style="display: inline-block; width: 100%; text-align: center"
            @click="doAction('fileConfiguration', record)"
          >
            {{ record.patchPackageCount || 0 }}
          </a>
        </template>
        <template slot="createTime" slot-scope="text">
          {{ text ? $options.filters.moment(text) : '_' }}
        </template>

        <template slot="formType" slot-scope="text">
          {{ text === 'AUTO' ? '自动创建' : '手动创建' }}
        </template>
        <template slot="svnDate" slot-scope="text">
          {{ text ? text : '-' }}
        </template>

        <span slot="action" slot-scope="text, record" class="tableOperateSty" style="display: flex;">
          <!-- <operation-menu
            :menus="record.versionType === 'TEST' ? tbRowMenus : [tbRowMenus[0]]"
            @clickaction="
              (key) => {
                doAction(key, record)
              }

            "
          ></operation-menu> -->

          <auth-button
            :auth="softwarePerms.partsSoftware.packageConfig"
            @click="handleConfig(record, true)"
            type="primary"
            :ghost="true"
            size="small"
            ><i class="iconfont icon-yanjing"/>查看</auth-button
          >
          <!-- 升级包配置 -->
          <!-- <auth-button
            :auth="softwarePerms.partsSoftware.packageConfig"
            @click="handleConfig(record)"
            type="primary"
            :ghost="true"
            size="small"
            >{{ $t('fileConfiguration') }}</auth-button
          > -->
          <!-- 编辑 -->
          <auth-button
            v-if="record.versionType === 'TEST'"
            :auth="softwarePerms.partsSoftware.edit"
            @click="handleAddEdit(record)"
            type="primary"
            :ghost="true"
            size="small"
            ><i class="iconfont icon-xiugai" />{{ $t('edit') }}</auth-button
          >
          <!-- 删除 -->
          <auth-button
            v-if="record.versionType === 'TEST'"
            :auth="softwarePerms.partsSoftware.delete"
            @click="deleteList(record)"
            type="danger"
            :ghost="true"
            size="small"
            ><i class="iconfont icon-shanchu3 deleteUlr" />{{ $t('delete') }}</auth-button
          >
        </span>
      </s-table>
    </div>
  </div>
</template>
<script>
import { mapMutations } from 'vuex'
import HasNoPermissionTip from '@/components/HasNoPermissionTip'
import TableEllipsis from '@/components/Ellipsis/TableEllipsis'
import AutoCreateVersion from './components/AutoCreateVersion'
import VersionTabs from './components/VersionTabs'
import OperationMenu from '@/components/OperationMenu'
import FileConfiguration from './components/FileConfiguration.vue'
import { STable } from '@/components'
import { minxinDrawerUse } from '@/utils/mixin'
import AuthButton from '@/components/AuthButton'
import VersionTypeSelect from '@/views/components/VersionTypeSelect'
import { softwarePerms } from '@/config/permission/index'
import { columns } from './components/config'
import { mapState } from 'vuex'
import CarModelCodeSelect from '@/views/components/CarModelCodeSelect'
import message from "ant-design-vue/lib/message";
export default {
  name: 'VersionList',
  mixins: [minxinDrawerUse],
  components: {
    TableEllipsis,
    HasNoPermissionTip,
    VersionTabs,
    FileConfiguration,
    VersionTypeSelect,
    OperationMenu,
    STable,
    AuthButton,
    CarModelCodeSelect,
  },
  data() {
    return {
      columns,
      softwarePerms,
      selectedEcuList: [], // 已选中ecu
      ecuList: [], // ecu过滤
      queryParam: {},
      actions: {
        // 创建版本
        ccv: {
          method: 'handleAddEdit',
        },
      },
      isSearch: false,
      deleteId: [],
      //表单类型下拉框option
      autoTestList: [
        { value: 'false', name: '手动创建' },
        { value: 'true', name: '自动创建' },
      ],
    }
  },
  watch: {
  },
  computed: {
    tbRowMenus() {
      return [
        {
          title: this.$t('fileConfiguration'),
          key: 'fileConfiguration',
          auth: softwarePerms.partsSoftware.packageConfig,
        },
        {
          title: this.$t('edit'),
          key: 'editVersion',
          auth: softwarePerms.partsSoftware.edit,
        },
        {
          title: this.$t('delete'),
          key: 'deleteVersion',
          auth: softwarePerms.partsSoftware.delete,
        },
      ]
    },
    ...mapState({
      instantUpdateTime: (state) => state.app.instantUpdateTime,
    }),
  },
  created() {
    const actionObj = this.actions[this.$route.query.action]
    // 从别的页面跳转过来调用相应的功能
    if (actionObj && actionObj.method) {
      this[actionObj.method]()
    }
  },
  mounted () {
    this.initiSelectValue()
  },
  methods: {
    // 下拉框 重置和初始化
    initiSelectValue() {
      this.queryParam = {}
      this.refreshData()
    },
    // 获取已选中ecu的下拉数据
    changeEcuList(value) {
      const vm = this
      vm.selectedEcuList = []
      if (value.length) {
        value.forEach((ecuModuleId) => {
          const selectItem = vm.ecuList.filter((item) => item.ecuModuleId === ecuModuleId)
          // vm.selectedEcuList = vm.selectedEcuList.concat(selectItem)
        })
      } else {
        vm.ecuList = []
      }
    },
    getEcuList(value = '') {
      const vm = this
      vm.ecuList = []
      vm.isSearch = false
      if (value) {
        vm.isSearch = true
        vm.$api
          .getAllEcu({ name: value.trim() })
          .then((response) => {
            const filterEcuList = vm.filterSelectEcuList(response.data || [])
            vm.ecuList = vm.selectedEcuList.concat(filterEcuList)
          })
          .catch(() => {
            vm.ecuList = vm.selectedEcuList
          })
      } else {
        // 无搜索时 下拉数据就是已选中的ecu
        vm.ecuList = vm.selectedEcuList
      }
    },
    // 从搜索出来的ecu中排除已选中的ecu
    filterSelectEcuList(searchEcuList) {
      const vm = this
      let filterEcu = searchEcuList
      const selectEcuModuleId = vm.queryParam.ecuModuleId
      if (selectEcuModuleId && selectEcuModuleId.length && filterEcu.length) {
        selectEcuModuleId.forEach((ecuModuleId) => {
          filterEcu = filterEcu.filter((item) => item.ecuModuleId !== ecuModuleId)
        })
      }
      return filterEcu
    },
    loadData(parameter) {
      const vm = this
      // 如果是全部则不传值给后端
      const JnqueryParam = JSON.parse(JSON.stringify(vm.queryParam))
      // eslint-disable-next-line no-restricted-syntax
      for (const key in JnqueryParam) {
        if (JnqueryParam[key] === '') {
          JnqueryParam[key] = undefined
        }
      }
      return vm.$api.getVersionList({ ...parameter, ...JnqueryParam })
    },
    // 新建编辑
    handleAddEdit(recordData = {}, type = 'version') {
      const vm = this 
      const vars = {
        recordData,
        type: type,
      }
      recordData.refreshData = this.refreshData
      const buttons = this.getRightDrawerFooterButtons()
      buttons[0].callback = (data, apiRes) => {
        if (apiRes.code !== 0) {
          return false
        }
        // 更新数据并切到升级包信息
        this.$api
          .versionInfor({
            id: apiRes.data || recordData.id, //新增返回的是ID、编辑返回 null
          })
          .then((res) => {
            if (!res.data) {
              return
            }
            if (!recordData.id) {
              recordData.id = apiRes.data
            }
            vars.recordData = { ...recordData, ...{ dependenceVersion: '' }, ...res.data }
            vars.type = 'package'
            // vm.showRightDrawer(VersionTabs, vm.$t('ecuVersion'), buttons, 'large', vars)
            vm.showRightDrawer(
              VersionTabs,
              vm.$t(recordData.id ? 'editcuversion' : 'newecuversion') + ' 【测试版】',
              buttons,
              'large',
              vars
            )
          })
        //不关闭right drawer
        return false
      }
      if (recordData.id) {
        //编辑
        vm.showRightDrawer(
          VersionTabs,
          vm.$t(recordData.id ? 'editcuversion' : 'newecuversion') + ' 【测试版】',
          buttons,
          'large',
          vars
        )
      } else {
        //新建
        vm.showRightDrawerNoReset(
          VersionTabs,
          vm.$t(recordData.id ? 'editcuversion' : 'newecuversion') + ' 【测试版】',
          buttons,
          'large',
          vars
        )
      }
    },
    //自动创建ecu版本
    autoAddVersion(recordData = {}, isDetail = false) {
      const vm = this
    //  vm.setInstantUpdateTime()
      const buttons = this.getRightDrawerFooterButtons({ key: '', method: 'addAutoECUVersion', callback: 'searchData' })
      //  recordData.isDetail = isDetail
       const vars = { recordData } 
      let title = '自动创建ECU版本' + ' 【测试版】'
      if (!isDetail) {
        vm.showRightDrawerNoReset(AutoCreateVersion, title, isDetail ? [] : buttons, 'medium', vars)
      }
    },
    //提交按钮
    addAutoECUVersion(data) {
    console.log(data);
    this.$api.autoCreateECUItem(data).then(res=>{
     this.refreshData(false) // 刷新页面
    })
    // 接口调用成功时
     this.removeRightDrawer()
    },
    //根据表单类型和版本类型才能查询自动测试版ECU
   /*  promptInfo(){
 if(!this.queryParam.versionType){
  message.warning({ content:'请将表单类型选择为测试版'})
 return
} 
    },*/
    // 升级包配置
    handleConfig(recordData, isDetail = false) {
      // this.handleAddEdit(recordData, 'package')
      const vm = this
      const vars = {
        recordData,
      }
     // vm.setInstantUpdateTime()
      recordData.refreshData = this.refreshData
      let title = this.$t('ecuVersion') + '【' + (recordData.versionType === 'TEST' ? '测试版' : '定版') + '】'
      this.showRightDrawer(FileConfiguration, title, [], 'large', vars)
    },
    // 新增编辑提交
    saveData(values) {
      const vm = this
      const params = vm.$commonFun.deepCopy(values)
      params.apiStr = undefined
      return new Promise((resolve, reject) => {
        vm.$api[values.apiStr](params)
          .then((res) => {
            vm.refreshData(!values.id)
            resolve(res)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    doAction(key, record) {
      const vm = this
      if (key === 'fileConfiguration') {
        vm.handleConfig(record)
      } else if (key === 'editVersion') {
        this.handleAddEdit(record)
      } else {
        vm.deleteList(record)
      }
    },
    // 批量删除
    deleteList(record) {
      const vm = this
      vm.deleteId = [record.id]
      this.$confirm({
        title: vm.$t('deleteSoftware'),
        content: '请确认是否删除选中的软件？ ' + `${record.name}` + ' 删除后将无法恢复',
        class: 'confirmStyle',
        icon: '<Icon >',
        width: 378,
        onOk: vm.deleteOk,
        onCancel() {},
      })
    },
    deleteOk() {
      const vm = this
      vm.$api.deleteVersion({ ids: vm.deleteId }).then(() => {
        vm.$message.success(vm.$t('successfullyDelete'))
        vm.refreshData(false) // 刷新页面
      })
    },
    refreshData(isToFirstPage = true) {
      const vm = this
      vm.$nextTick(() => {
        vm.$refs.table.refresh(isToFirstPage)
      })
    },
  },
}
</script>
<style scoped>
</style>
